<?php

/**
 * Created by PhpStorm.
 * User: 小灰灰
 * Date: 2022-06-21
 * Time: 16:11:47
 * Info:
 */

namespace app\api\controller;

use support\Request;
use app\common\model\UserToken as UserTokenModel;

class IndexController extends ApiController
{

    public function __construct()
    {
        parent::__construct();
    }

    public function index(Request $request)
    {
        $api    = config('api');
        $method = explode('.', $request->input('method'));
        if (count($method) != 2 && count($method) != 3) {
            //method参数结构错误
            return $this->error('method参数结构错误');
        }

        if (isset($api[$method[0]])) {
            $cname = $api[$method[0]]['code'];
        } else {
            return $this->error('method参数1不存在');
        }

        if (isset($api[$method[0]]['method'][$method[1]])) {
            $aname = $api[$method[0]]['method'][$method[1]]['code'];
        } else {
            return $this->error('method参数2不存在');
        }

        //判断是否需要登陆
        if ($api[$method[0]]['method'][$method[1]]['is_login']) {
            $token = request()->input('token');
            if ( ! $token) {
                return $this->error('请先登录');
            }
            $userTokenModel = new UserTokenModel();
            $result         = $userTokenModel->checkToken($token);

            if (empty($result) || empty($result['code'])) {
                return $this->error('用户身份过期请重新登录');
            }

            $this->userId = $result['data']['user_id'];

        } else {
            $this->userId = 0;
        }

        try {
            $cname = $cname.'Controller';
            $obj   = '\\app\\api\\controller\\'.$cname;
            $c     = new $obj();
            $c->setInit($this->userId);
        } catch (\Exception $e) {
            return $this->error('操作失败，请重试1');
        }
        if ( ! method_exists($c, $aname)) {
            return $this->error('对应的控制器方法名不存在，请重试');
        }

        return $c->$aname();

    }
}

